package com.gitee.xiao;

import org.opencv.core.*;
import org.opencv.imgproc.Imgproc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author wang xiao
 * date 2024/7/10
 */
@RestController
public class FaceDataController {

    private static final Logger logger = LoggerFactory.getLogger(FaceDataController.class);

    @Autowired
    private FaceDataService faceDataService;

    static {
        // 加载OpenCV库
        nu.pattern.OpenCV.loadLocally();
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFaceData(@RequestParam("image") MultipartFile file,
                                                 @RequestParam("description") String description) {
        try {
            // 读取图像数据
            byte[] imageData = file.getBytes();
            // 提取人脸特征
            byte[] featureData = extractFaceFeature(imageData);

            faceDataService.saveFaceData(imageData, featureData, description);
            logger.info("人脸数据上传成功，描述: {}", description);
            return ResponseEntity.ok("人脸数据上传成功");
        } catch (IOException e) {
            logger.error("上传人脸数据失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传人脸数据失败");
        }
    }

    @GetMapping("/retrieve/{id}")
    public ResponseEntity<FaceData> retrieveFaceData(@PathVariable Long id) {
        FaceData faceData = faceDataService.getFaceDataById(id);
        logger.info("获取到人脸数据，ID: {}", id);
        return ResponseEntity.ok(faceData);
    }

    @PostMapping("/findMostSimilar")
    public ResponseEntity<FaceData> findMostSimilarFace(@RequestParam("image") MultipartFile file) {
        try {
            byte[] targetImageData = file.getBytes();
            byte[] targetFeatureData = extractFaceFeature(targetImageData);

            FaceData mostSimilarFace = faceDataService.findMostSimilarFace(targetFeatureData);
            logger.info("找到最相似的人脸数据，ID: {}", mostSimilarFace.getId());
            return ResponseEntity.ok(mostSimilarFace);
        } catch (IOException e) {
            logger.error("查找最相似的人脸数据失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    // 从图像中提取人脸特征
    private byte[] extractFaceFeature(byte[] imageData) {
        // 示例中以简单的图像处理方法代替，实际应用中需要使用更复杂的人脸特征提取技术
        Mat image = Mat.eye(3, 3, CvType.CV_8UC1); // 创建一个空白矩阵
        // OpenCV用于处理图像的例子：
        Mat image = Imgproc.imdecode(new MatOfByte(imageData), Imgcodecs.IMREAD_UNCHANGED);
        Mat resizedImage = new Mat();
        Imgproc.resize(image, resizedImage, new Size(100, 100));
        return resizedImage.dataAddr();
    }
}
